import Vue from 'vue'
import Router from 'vue-router'
import store from '@/stores'
import { wxAuth } from '@/libs/service'

Vue.use(Router)

let routes = [
    { path: '/', redirect: '/page/home' },
    // 处理微信授权页面
    { path: '/wxAuth', name: 'wxAuth', component: () => import('@/views/wxAuth.vue') },
    // 微信jsdk demo
    { path: '/wxShare/index', name: 'wxShareDemo', component: () => import('@/views/weShare/index.vue') },
    // 入口
    { path: '/page/:tab', name: 'index', component: () => import('@/views/index.vue') },
    // 首页
    { path: '/home', name: 'home', component: () => import('@/views/home/index.vue') },
    //
    { path: '/center', name: 'center', component: () => import('@/views/center/index.vue') },
    // 个人中心
    { path: '/my', name: 'my', component: () => import('@/views/my/index.vue') },

    { path: '/error', name: 'abnormal', component: () => import('@/views/common/error.vue') },
    { path: '*', name: '404Error', component: () => import('@/views/common/404.vue') }
]

const router = new Router({
    mode: 'history',
    base: process.env.VUE_APP_PUBLIC_PATH,
    routes
})

router.beforeEach((to, from, next) => {
    let code = to.query.code
    let state = to.query.state
    // code state 微信授权后标志 需要跟后台交互
    // http://xxx.com?code=011iw0l60KMpdG1hlUm60x3Jk60iw0l2&state=wechat
    store.commit('wechat/setSignUrl', to)
    // let token = Vue.prototype.$ls.getItem('token')
    if (code && state) {
        let param = []
        for (const key in to.query) {
            if (key != 'code' && key != 'state') {
                param.push(key + '=' + to.query[key])
            }
        }
        wxAuth(code).then(() => {
            router.replace(`${to.path}?${param.join('&')}`)
            next()
        })
    } else {
        if (to.name != from.name) {
            store.commit('keepalive/setRoute', {
                to: to,
                from: from
            })
        }
        next()
    }
})

router.afterEach(to => {
    if (process.env.NODE_ENV != 'production') {
        console.info('keepalive: ' + store.state.keepalive.list)
    }
})

export default router
